
<template>
<!-- 
    ruleForm收集表单数据对象
    rules 规则
 -->
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="ruleForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="ruleForm.password"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="login">登录</el-button>
    <el-button >重置</el-button>
  </el-form-item>
</el-form>
</template>

<script>
  export default {
    data() {
      return {
        ruleForm: {
        username:'10086',
        password:'123'
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { pattern:/^1\d{3,5}$/, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
           password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min:3,max:5, message: '密码格式不正确', trigger: 'blur' }
          ],
          
        }
      };
    },
    methods: {
    async login(){
       try {
        console.log('登录');
        await this.$refs.ruleForm.validate()
        //  1.发送请求
        const res = await this.$axios.post('/login', this.ruleForm)
        console.log('登录结果',res.data);
        const{message,statusCode,data}=res.data
    if(statusCode === 200){
        // 2.提示登录成功
        this.$message.success(message)
        // 3.保存本地token
        localStorage.setItem('token',data.token)
        localStorage.setItem('user',JSON.stringify(data.user))
        // 4.跳转
        this.$router.push('/home/list')
       }else{
           this.$message.error(message)
       }
       } catch (error) {
           this.$message.error('校验失败')
       }
     },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style lang='less' scoped >
.el-form {
  margin: 0 auto;
  margin-top: 50px;
  width: 400px;
  border: 5px solid #000;
  padding: 20px;
  border-radius: 20px;
  .el-button{
    margin-right: 50px;
  }
}
</style>